package com.ruoyi.common.core.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unused")
public class HttpRequestUtils {

    /**
     * 发送 HTTP POST请求的方法（可更改）
     * @param Url 请求的 URL
     * @param params 携带的请求体 每个键值对都会封装成 JSON
     * @return 返回的 JSON结果
     */
    public static String HttpPost(String Url, Map<String,String> params){
        String resp = null;
        JSONObject obj = new JSONObject();
        obj.putAll(params);
        String query = obj.toString();
        try {
            URL url = new URL(Url); // URL地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/json");
            connection.connect();
            try (OutputStream os = connection.getOutputStream()) {
                os.write(query.getBytes(StandardCharsets.UTF_8));
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String lines;
                StringBuffer sbf = new StringBuffer();
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), StandardCharsets.UTF_8);
                    sbf.append(lines);
                }
                resp = sbf.toString(); //返回的数据
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JSONObject json = (JSONObject)JSON.parse(resp);
        }
        return resp;
    }

    /**
     * 获取共青团省平台token
     * @return token
     */
    public static String getProvinceSystemToken(){
        Map<String,String> params = new HashMap<>();
        params.put("appId","ZYSC_YB");
        params.put("secert","123456");
        String resp = HttpPost("http://data-tran-yb.nvnbd.com/api/data/getToken", params);
        JSONObject jsonObject = JSONObject.parseObject(resp);
        return jsonObject.get("data").toString();
    }

    /**
     * 向共青团省平台更新用户的鲜豆
     * @param user_id  用户ID
     * @param change_star 变化的鲜豆数（可正可负）
     * @return 消息结果 （请求成功 或 请求失败）
     */
    public static String ProvinceSystemBeanAction(long user_id,int change_star){
        String token = HttpRequestUtils.getProvinceSystemToken(); //获取省平台token
        Map<String,String> params = new HashMap<>();
        params.put("token",token);
        params.put("id",String.valueOf(user_id));
        params.put("score",String.valueOf(change_star));
        params.put("nowTime",String.valueOf(new Date().getTime()));
        String resp = HttpPost("http://data-tran-yb.nvnbd.com/api/user/scoreDeu", params);
        JSONObject jsonObject = JSONObject.parseObject(resp);
        System.out.println(jsonObject.toString());
        return (String) jsonObject.get("msg");
    }
}
